import org.apache.http.HttpException

import javax.servlet.http.HttpServletResponse
import wsd.sys.jdbcManager
import wsd.appsys.sp.*
import javax.faces.context.FacesContext
import org.primefaces.event.FileUploadEvent
import org.primefaces.model.file.UploadedFile
import java.text.SimpleDateFormat
import com.lowagie.text.DocumentException
import com.lowagie.text.pdf.BaseFont
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper
import java.awt.Color
import groovy.sql.Sql
import java.sql.Blob
import java.io.FileOutputStream

public execute(o) {
    return new ddd(o)
}

class ddd {

    def mypara

    public ddd(m) {
        this.mypara = m;
    }

    def _url = "";
    def _json = "";
    def _return = "";

    def openapi() {
        println("============" + _url)
        println("============" + _json)
        if (_url == null || _url.equals("") || _json == null || _json.equals("")) {
            mypara.msg("地址、URL必填");
            return;
        }
        def json = TokenTest.openapi(_url, _json);
        println("json============" + json)
        _return = TokenTest.openapi2(_url, _json, json);
        println("_return============" + _return)

//        org.primefaces.PrimeFaces.current().ajax().update("maintab:openapiForm:card2");
    }


}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;

import com.google.gson.Gson;

import nccloud.open.api.auto.token.factory.APIUtilsFactory;
import nccloud.open.api.auto.token.factory.NCCVersionEnum;
import nccloud.open.api.auto.token.itf.IAPIUtils;
import nccloud.open.api.auto.token.cur.utils.CompressUtil;
import nccloud.open.api.auto.token.cur.utils.Decryption;
import nccloud.open.api.auto.token.cur.utils.Encryption;

//import nccloud.open.api.auto.token.cur.utils.ResultMessageUtil;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.open.api.auto.token.cur.utils.SHA256Util;

/**
 * 1.从resources/config.properties中读取测试api相关的数据 2.运行程序，测试查看测试结果
 *
 * @author lizhmf
 * @date 2019年6月20日上午10:53:11
 */
public class Test {

    private static String client_secret = "2aa7460b1ccc471a84f7";
    private static String pubKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqCFdcbMQJ2cHPIffjul8fSNM+WZvI4xz9FAoni5pSVqXaZAtTNIVxS2SUpj3byIMBbRoLqXkXyAF9G/TMErVwTaH0WEGpCEfLnU7acBMTimGpwjWmCTPwaiD0JqB14HYjegdSjt7BOVrLbV2e4oKzC/FMf0dTZh7gKmfg8hjhHKmyQD13npWRNB+/+9IQWZLs493JlfPSObYpPyX+WTCNBGqsAyme0MVoYMJ8RTyidylnBbShFBkNMB+Z4EYXtIX5dUiTDyu6RuOgAVilPR/UHMihTAtu8KMJWnXaSDym6y4QH9dw3tlJms6lwDeVDynTBYu/myiNn4pNBxUwDb9RQIDAQAB";
    private static String client_id = "ESB";
    private static String username = "Wangcs";
    private static String pwd = "bip12345.";
    private static String busi_center = "001";
    // 获取token方式
    private static String grant_type = "password";
    // 服务器ip：port
    private static String baseUrl = "http://10.1.1.226:10088";
    private static String secret_level = "L0";
    private static String requestBody = "{\n" +
            "  \"csaleorderid\": [\n" +
            "    \"1001A11000000000OO2D\"\n" +
            "  ]\n" +
            "}";
    // openapi请求路径
    private static String apiUrl = "/nccloud/api/so/saleorder/approve";

    public static String token = null;
    public static String repeat_check = "Y";
    public static String busi_id = "1234";

    public static void main(String[] args) {
        try {
            // 请求token
            token = getToken();
            System.out.println("getTokenData:" + token);
            if (token != null) {
                // 测试openapi
                testApi(token);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过refresh_token重新获取token
     *
     * @param refresh_token
     * @return
     * @throws UnsupportedEncodingException
     * @throws Exception
     */
    private static String getTokenByRefreshToken(String refresh_token) throws UnsupportedEncodingException, Exception {
        Map<String, String> paramMap = new HashMap<String, String>();
        // 密码模式认证
        paramMap.put("grant_type", "refresh_token");
        // 第三方应用id
        paramMap.put("client_id", client_id);
        // 第三方应用secret 公钥加密
        paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8"));
        // 签名
        String sign = SHA256Util.getSHA256(client_id + client_secret + refresh_token + pubKey);
        paramMap.put("signature", sign);

        String url = baseUrl + "/nccloud/opm/accesstoken";
        String mediaType = "application/x-www-form-urlencoded";
        String token = doPost(url, paramMap, mediaType, null, "");
        return token;
    }

    private static String getToken() throws Exception {
        String token = null;
        if ("password".equals(grant_type)) {
            // 密码模式
            token = getTokenByPWD();
        } else if ("client_credentials".equals(grant_type)) {
            // 客户端模式
            token = getTokenByClient();
        } else if ("authorization_code".equals(grant_type)) {
            // TODO 页面跳转
            // 授权码模式
        }
        return token;
    }

    /**
     * 客户端模式获取token
     *
     * @return
     * @throws Exception
     */
    private static String getTokenByClient() throws Exception {
        Map<String, String> paramMap = new HashMap<String, String>();
        // 密码模式认证
        paramMap.put("grant_type", "client_credentials");
        // 第三方应用id
        paramMap.put("client_id", client_id);
        // 第三方应用secret 公钥加密
        paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8"));
        // 账套编码
        paramMap.put("biz_center", busi_center);
        // // TODO 传递数据源和ncc登录用户
        // paramMap.put("dsname", "TM_0614");
        // paramMap.put("usercode", "1");

        // 签名
        String sign = SHA256Util.getSHA256(client_id + client_secret + pubKey);
        paramMap.put("signature", sign);

        String url = baseUrl + "/nccloud/opm/accesstoken";
        String mediaType = "application/x-www-form-urlencoded";
        String token = doPost(url, paramMap, mediaType, null, "");
        return token;
    }

    /**
     * 密码模式获取token
     *
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unused")
    private static String getTokenByPWD() throws Exception {
        Map<String, String> paramMap = new HashMap<String, String>();
        // 密码模式认证
        paramMap.put("grant_type", "password");
        // 第三方应用id
        paramMap.put("client_id", client_id);
        // 第三方应用secret 公钥加密
        paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8"));
        // ncc用户名
        paramMap.put("username", username);
        // 密码 公钥加密
        paramMap.put("password", URLEncoder.encode(Encryption.pubEncrypt(pubKey, pwd), "utf-8"));
        // 账套编码
        paramMap.put("biz_center", busi_center);
        // 签名
        String sign = SHA256Util.getSHA256(client_id + client_secret + username + pwd + pubKey);
        paramMap.put("signature", sign);

        String url = baseUrl + "/nccloud/opm/accesstoken";
        String mediaType = "application/x-www-form-urlencoded";
        String token = doPost(url, paramMap, mediaType, null, "");
        return token;
    }

    /**
     * 请求openapi
     *
     * @param token
     * @param security_key
     *                         请求body参数加密压缩用的key
     * @throws Exception
     */
    private static void testApi(String token) throws Exception {
        // token转对象，获取api访问所用token和secret
        println("=========================" + token);
        println("=========================" + token.getClass());
        return;
        Map<String, String> data = (Map<String, String>) token.getData();
        String access_token = data.get("access_token");
        String security_key = data.get("security_key");
        String refresh_token = data.get("refresh_token");
        System.out.println("【ACCESS_TOKEN】:" + access_token);

        // 请求路径
        String url = baseUrl + apiUrl;
        // header 参数
        Map<String, String> headermap = new HashMap<>();
        headermap.put("access_token", access_token);
        headermap.put("client_id", client_id);

        StringBuffer sb = new StringBuffer();
        sb.append(client_id);
        if (StringUtils.isNotBlank(requestBody)) {
            // sb.append(requestBody.replaceAll("\\s*|\t|\r|\n", "").trim());
            sb.append(requestBody);
        }
        sb.append(pubKey);
        String sign = SHA256Util.getSHA256(sb.toString());
        headermap.put("signature", sign);

        if (StringUtils.isNotBlank(busi_id)) {
            headermap.put("busi_id", busi_id);
        }
        if (StringUtils.isNotBlank(repeat_check)) {
            headermap.put("repeat_check", repeat_check);
        }
        headermap.put("ucg_flag", "y");

        String mediaType = "application/json;charset=utf-8";

        // 表体数据json
        // 根据安全级别选择加密或压缩请求表体参数
        String json = dealRequestBody(requestBody, security_key, secret_level);

        // 返回值
        String result = doPost(url, null, mediaType, headermap, json);
        String result2 = dealResponseBody(result, security_key, secret_level);
        System.out.println("【RESULT】:" + result);
        // System.out.println("result解密:" + result2);
    }

    private static String dealResponseBody(String source, String security_key, String level) throws Exception {
        String result = null;

        if (StringUtils.isEmpty(level) || SecretConst.LEVEL0.equals(level)) {
            result = source;
        } else if (SecretConst.LEVEL1.equals(level)) {
            result = Decryption.symDecrypt(security_key, source);
        } else if (SecretConst.LEVEL2.equals(level)) {
            result = CompressUtil.gzipDecompress(source);
        } else if (SecretConst.LEVEL3.equals(level)) {
            result = CompressUtil.gzipDecompress(Decryption.symDecrypt(security_key, source));
        } else if (SecretConst.LEVEL4.equals(level)) {
            result = Decryption.symDecrypt(security_key, CompressUtil.gzipDecompress(source));
        } else {
            throw new Exception("无效的安全等级");
        }

        return result;
    }

    // 根据安全级别设置，表体是否加密或压缩
    private static String dealRequestBody(String source, String security_key, String level) throws Exception {
        String result = null;
        if (StringUtils.isEmpty(level) || SecretConst.LEVEL0.equals(level)) {
            result = source;
        } else if (SecretConst.LEVEL1.equals(level)) {
            result = Encryption.symEncrypt(security_key, source);
        } else if (SecretConst.LEVEL2.equals(level)) {
            result = CompressUtil.gzipCompress(source);
        } else if (SecretConst.LEVEL3.equals(level)) {
            result = Encryption.symEncrypt(security_key, CompressUtil.gzipCompress(source));
        } else if (SecretConst.LEVEL4.equals(level)) {
            result = CompressUtil.gzipCompress(Encryption.symEncrypt(security_key, source));
        } else {
            throw new Exception("无效的安全等级");
        }

        return result;
    }

    /**
     * 发送post请求
     *
     * @param baseUrl
     * @param paramMap
     * @param mediaType
     * @param headers
     * @param json
     * @return
     */
    private static String doPost(String baseUrl, Map<String, String> paramMap, String mediaType, Map<String, String> headers, String json) {

        HttpURLConnection urlConnection = null;
        InputStream in = null;
        OutputStream out = null;
        BufferedReader bufferedReader = null;
        String result = null;
        try {
            StringBuffer sb = new StringBuffer();
            sb.append(baseUrl);
            if (paramMap != null) {
                sb.append("?");
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    sb.append(key + "=" + value).append("&");
                }
                baseUrl = sb.toString().substring(0, sb.toString().length() - 1);
            }

            URL urlObj = new URL(baseUrl);
            urlConnection = (HttpURLConnection) urlObj.openConnection();
            urlConnection.setConnectTimeout(50000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.addRequestProperty("content-type", mediaType);
            if (headers != null) {
                for (String key : headers.keySet()) {
                    urlConnection.addRequestProperty(key, headers.get(key));
                }
            }
            out = urlConnection.getOutputStream();
            out.write(json.getBytes("utf-8"));
            out.flush();
            int resCode = urlConnection.getResponseCode();
            if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED || resCode == HttpURLConnection.HTTP_ACCEPTED) {
                in = urlConnection.getInputStream();
            } else {
                in = urlConnection.getErrorStream();
            }
            bufferedReader = new BufferedReader(new InputStreamReader( in, "utf-8") );
            StringBuffer temp = new StringBuffer();
            String line = bufferedReader.readLine();
            while (line != null) {
                temp.append(line).append("\r\n");
                line = bufferedReader.readLine();
            }
            String ecod = urlConnection.getContentEncoding();
            if (ecod == null) {
                ecod = Charset.forName("utf-8").name();
            }
            result = new String(temp.toString().getBytes("utf-8"), ecod);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            urlConnection.disconnect();
        }
        return result;
    }

    class SecretConst {
        /**
         * LEVEL0 不压缩、不加密
         */
        public static final String LEVEL0 = "L0";
        /**
         * LEVEL1 只加密、不压缩
         */
        public static final String LEVEL1 = "L1";
        /**
         * LEVEL2 只压缩、不加密
         */
        public static final String LEVEL2 = "L2";
        /**
         * LEVEL3 先压缩、后加密
         */
        public static final String LEVEL3 = "L3";
        /**
         * LEVEL4 先加密、后压缩
         */
        public static final String LEVEL4 = "L4";
    }
}


import nccloud.open.api.auto.token.factory.APIUtilsFactory;
import nccloud.open.api.auto.token.factory.NCCVersionEnum;
import nccloud.open.api.auto.token.itf.IAPIUtils;

public class TokenTest {

    public static void main(String[] args) throws Exception {

    }

    public static String openapi(String urlStr, String jsonStr) throws Exception {
        IAPIUtils util = null;
        // 传参版本号或版本枚举获取工具类
        util = APIUtilsFactory.getAPIUtils(NCCVersionEnum.NCC2111);
        // 服务地址ip
        String ip = "oa.bestcomm.cn";
        // 服务端口号
        String port = "10088";
        // 账套编码，开发环境使用develop，生产环境需要使用用root账号登录，在“系统管理”节点查看账套编码
        String busi_center = "01";
        // 第三方应用编码
        String app_id = "ESB";
        // app_secret，用于请求加签
        String app_secret = "0b0353d94b0d4bb7a0c3";
        // 公钥，加解密使用
        String public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjPqiC7n0Jx2TLrRJMeXajlj2aYJUcTF0AhIC3gEGbQAwvX0Revwb08bdhI54usqY4nnrGUb/nrQ8BCPigzwDb4rWTxrVKzqO477aKsYH9S8TcyFPBEt2vp6mDjZ630jmy9KvkJTfcgsJgKQsH5mlPvidHFn4d2EnEdd6+fZH2Z52rF6nJyalTlrJCmu05Hlepk/lW7r+ldA3ZZ/DdoUkHk4b4Veopyxke/oKYMqMtaPGJSJ9C+2j9ksuPC17tAS1yz2u1WRFdg6d4soZECrHWlOLbTebMAG5mqb+dqiTRdBGkASYMNmRmBUrc3rC9uUeXAhV5y1iuy3ibK1XROhBPwIDAQAB";
        // ncc用户名
        String ncc_user = "";
        // ncc用户密码
        String password = "";
        // 公有云租户id
        String tenant_id = null;
        // 加密等级
        String secret_level = "L0";
        // 授权模式，客户端模式为client，密码模式为：password
        String grant_type = "password";

        // 初始化方法1
        util.init(ip, port, busi_center, app_id, app_secret, public_key, ncc_user, password);
        // 初始化方法2，tenant_id、secret_level、grant_type这三个参数也可以通过setter注入
        // util.init(ip, port, busi_center, app_id, app_secret, public_key, ncc_user, password, tenant_id, secret_level, grant_type);

        // 获取token
        String token = util.getToken();
        return token;
    }

    public static String openapi2(String urlStr, String jsonStr, String token) throws Exception {
        IAPIUtils util = null;
        // 传参版本号或版本枚举获取工具类
        util = APIUtilsFactory.getAPIUtils(NCCVersionEnum.NCC2111);
        // 服务地址ip
        String ip = "oa.bestcomm.cn";
        // 服务端口号
        String port = "10088";
        // 账套编码，开发环境使用develop，生产环境需要使用用root账号登录，在“系统管理”节点查看账套编码
        String busi_center = "01";
        // 第三方应用编码
        String app_id = "ESB";
        // app_secret，用于请求加签
        String app_secret = "2aa7460b1ccc471a84f7";
        // 公钥，加解密使用
        String public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjPqiC7n0Jx2TLrRJMeXajlj2aYJUcTF0AhIC3gEGbQAwvX0Revwb08bdhI54usqY4nnrGUb/nrQ8BCPigzwDb4rWTxrVKzqO477aKsYH9S8TcyFPBEt2vp6mDjZ630jmy9KvkJTfcgsJgKQsH5mlPvidHFn4d2EnEdd6+fZH2Z52rF6nJyalTlrJCmu05Hlepk/lW7r+ldA3ZZ/DdoUkHk4b4Veopyxke/oKYMqMtaPGJSJ9C+2j9ksuPC17tAS1yz2u1WRFdg6d4soZECrHWlOLbTebMAG5mqb+dqiTRdBGkASYMNmRmBUrc3rC9uUeXAhV5y1iuy3ibK1XROhBPwIDAQAB";
        // ncc用户名
        String ncc_user = "";
        // ncc用户密码
        String password = "";
        // 公有云租户id
        String tenant_id = null;
        // 加密等级
        String secret_level = "L0";
        // 授权模式，客户端模式为client，密码模式为：password
        String grant_type = "password";

        // 初始化方法1
        util.init(ip, port, busi_center, app_id, app_secret, public_key, ncc_user, password);
        // 初始化方法2，tenant_id、secret_level、grant_type这三个参数也可以通过setter注入
        // util.init(ip, port, busi_center, app_id, app_secret, public_key, ncc_user, password, tenant_id, secret_level, grant_type);

        // 请求的OpenAPI接口地址，注意nccloud前面没有"/"
        String apiuri = urlStr;
        util.setApiUrl(apiuri);
        // 携带token访问接口，获取结果
        String result = util.getAPIRetrun(token, jsonStr);
        return result;
    }

}



